package com.sky.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author xushupeng
 * @Date 2024-12-28 11:35
 */
@Component
@Slf4j
public class OSSUploadUtils {
    //阿里oss域名

    @Value("${sky.alioss.domain}")
    private String ALI_DOMAIN;//访问域名

    //生成文件名
    @Value("${sky.alioss.endpoint}")   //@value注解必须在spring bean对象中使用
    private  String endPoint ;
    // ID // LTAI5t9zF4K3iz4GPFDjfVQB
    //KEY // UCtA3Zttf4LbFsW8hk8BsXQE0kGvhh
    @Value("${sky.alioss.access-key-id}")
    private  String acessKeyID ;
    @Value("${sky.alioss.access-key-secret}")
    private  String acessKeySecret;
    @Value("${sky.alioss.bucket-name}")
    private String bucketName;

    //静态方法中不能使用实例变量  静态方法只能访问静态变量

    public String uploadImage(MultipartFile file) throws IOException {

//        System.out.println("endPoint is "+endPoint);
//        System.out.println("acessKeyID is "+acessKeyID);
//        System.out.println("acessKeySecret is "+acessKeySecret);

        String originalFileName = file.getOriginalFilename();
        String pre = null;//左闭右开区间 //获取文件名
        if (originalFileName != null) {
            pre = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
        }
        String ext = "." + originalFileName.substring(originalFileName.lastIndexOf('.')+1);//文件后缀 .png
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(3,11); //将uuid里面的”-“替代
        String fileName = pre + "_"+uuid + ext; //最终文件名的组成
        log.info("oss file url  is "+fileName);
        //oss客户端对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, acessKeyID, acessKeySecret);
        ossClient.putObject(bucketName, fileName, file.getInputStream()); //三个参数 "oss的bucket名字"
        ossClient.shutdown();//关闭
        // oss客户端对象
        return ALI_DOMAIN + fileName;//访问路径

    }
    public  String deleteFile(String fileName) {
        //oss客户端对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, acessKeyID, acessKeySecret);
        ossClient.deleteObject(bucketName, fileName);//filename  xxxx.jpg
        return fileName + "删除成功";

    }
}